//
//  BasicAnimationView.m
//  TotalDemo
//
//  Created by gujian on 16/5/18.
//  Copyright © 2016年 gujian. All rights reserved.
//

#import "BasicAnimationView.h"

@interface BasicAnimationView()

@property (nonatomic, assign) BasicTransform basicTransfrom;

@end

@implementation BasicAnimationView

- (instancetype)initWithFrame:(CGRect)frame BasicTransform:(BasicTransform)basicTransform
{
    self = [super initWithFrame:frame];
    if (self) {
        _basicTransfrom = basicTransform;
        CAGradientLayer *layer = [CAGradientLayer new];
        layer.colors = @[(__bridge id)([UIColor randomColor].CGColor),(__bridge id)([UIColor randomColor].CGColor)];
        layer.startPoint = CGPointMake(0, 0);
        layer.endPoint = CGPointMake(1, 1);
        layer.frame = self.bounds;
        [self.layer addSublayer:layer];
        [self addTapGesture];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    return [self initWithFrame:frame BasicTransform:BasicTransformX];
}

- (void)addTapGesture
{
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [self addGestureRecognizer:tapGesture];
}

- (void)handleTapGesture:(UITapGestureRecognizer *)gesture
{
    CATransform3D orginTransform = self.layer.transform;
    CATransform3D targetTransform = orginTransform;

    
    CGFloat transfromX = 0;
    CGFloat transfromY = 0;
    CGFloat transfromZ = 0;
    
    if (_basicTransfrom & BasicTransformX) {
        transfromX = 0.5;
    }
    
    if (_basicTransfrom & BasicTransformY) {
        transfromY = 0.5;
    }
    
    if (_basicTransfrom & BasicTransformZ) {
        transfromZ = 0.5;
    }
    
    targetTransform = CATransform3DRotate(targetTransform, M_PI, transfromX, transfromY, transfromZ);
    
    
    [UIView animateWithDuration:4.0 animations:^{
        self.userInteractionEnabled = NO;
        self.layer.transform = targetTransform;
    } completion:^(BOOL finished) {
        self.userInteractionEnabled = YES;
        self.layer.transform = orginTransform;
    }];
}

@end
